package com.castle.fortress.admin.study.course.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.annotation.CastleLog;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.study.course.dto.StudyCourseClassifyDto;
import com.castle.fortress.admin.study.course.dto.StudyCourseDto;
import com.castle.fortress.admin.study.course.entity.StudyCourseClassifyEntity;
import com.castle.fortress.admin.study.course.service.StudyCourseClassifyService;
import com.castle.fortress.admin.study.course.service.StudyCourseService;
import com.castle.fortress.admin.study.course.service.StudyCoursewareService;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.CourseStatusEnum;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 课程/课件分类表 控制器
 *
 * @author castle
 * @since 2023-01-30
 */
@Api(tags="课程/课件分类表管理控制器")
@Controller
public class StudyCourseClassifyController {
    @Autowired
    private StudyCourseClassifyService studyCourseClassifyService;
    @Autowired
    private StudyCoursewareService studyCoursewareService;
    @Autowired
    private StudyCourseService studyCourseService;

	/**
	 * 课程/课件分类表的分页展示
	 * @param studyCourseClassifyDto 课程/课件分类表实体类
	 * @param current 当前页
	 * @param size  每页记录数
	 * @return
	 */
    @CastleLog(operLocation="课程/课件分类表",operType = OperationTypeEnum.QUERY)
	@ApiOperation("课程/课件分类表分页展示")
	@GetMapping("/study/course/studyCourseClassify/page")
	@ResponseBody
	@RequiresPermissions("study:course:studyCourseClassify:pageList")
	public RespBody<IPage<StudyCourseClassifyDto>> pageStudyCourseClassify(StudyCourseClassifyDto studyCourseClassifyDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
		Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
		Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
		Page<StudyCourseClassifyDto> page = new Page(pageIndex, pageSize);
			IPage<StudyCourseClassifyDto> pages = studyCourseClassifyService.pageStudyCourseClassifyExtends(page, studyCourseClassifyDto);

		return RespBody.data(pages);
	}

    /**
     * 课程/课件分类表的树形展示
     * @param studyCourseClassifyDto 课程/课件分类表实体类
     * @return
     */
    @CastleLog(operLocation="课程/课件分类表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("课程/课件分类表分页展示")
    @GetMapping("/study/course/studyCourseClassify/tree")
    @ResponseBody
    public RespBody<List<StudyCourseClassifyDto>> treeStudyCourseClassify(StudyCourseClassifyDto studyCourseClassifyDto){
	    List<StudyCourseClassifyDto> list = studyCourseClassifyService.listStudyCourseClassify(studyCourseClassifyDto);
	    //展示时需要展示到顶级
	    Set<Long> ids=new HashSet<>();
	    for(StudyCourseClassifyDto s:list){
		    ids.add(s.getId());
	    }
	    List<Long> parentId =new ArrayList<>();
	    List<StudyCourseClassifyDto> parentList=new ArrayList<>();
	    for(StudyCourseClassifyDto s:list){
		    if(s.getParentId()!=null&&!ids.contains(s.getParentId())){
			    parentId.add(s.getParentId());
		    }
	    }
	    if(!parentId.isEmpty()){
		    QueryWrapper<StudyCourseClassifyEntity> wrapper=new QueryWrapper<>();
		    wrapper.in("id",parentId);
            wrapper.orderByDesc("sort");
		    parentList= ConvertUtil.transformObjList(studyCourseClassifyService.list(wrapper),StudyCourseClassifyDto.class);
		    list.addAll(parentList);
	    }
	    do{
		    parentId =new ArrayList<>();
		    for(StudyCourseClassifyDto s:parentList){
			    if(s.getParentId()!=null){
				    parentId.add(s.getParentId());
			    }
		    }
		    if(!parentId.isEmpty()){
			    QueryWrapper<StudyCourseClassifyEntity> wrapper=new QueryWrapper<>();
			    wrapper.in("id",parentId);
                wrapper.orderByDesc("sort");
			    parentList= ConvertUtil.transformObjList(studyCourseClassifyService.list(wrapper),StudyCourseClassifyDto.class);
			    list.addAll(parentList);
		    }
	    }while(!parentId.isEmpty());
	    return RespBody.data(ConvertUtil.listToTree(list));
    }

    /**
     * 课程/课件分类表的列表展示
     * @param studyCourseClassifyDto 课程/课件分类表实体类
     * @return
     */
    @CastleLog(operLocation="课程/课件分类表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("课程/课件分类表列表展示")
    @GetMapping("/study/course/studyCourseClassify/list")
    @ResponseBody
    public RespBody<List<StudyCourseClassifyDto>> listStudyCourseClassify(StudyCourseClassifyDto studyCourseClassifyDto){
        List<StudyCourseClassifyDto> list = studyCourseClassifyService.listStudyCourseClassify(studyCourseClassifyDto);
        return RespBody.data(list);
    }

    /**
     * 课程/课件分类表保存
     * @param studyCourseClassifyDto 课程/课件分类表实体类
     * @return
     */
    @CastleLog(operLocation="课程/课件分类表",operType = OperationTypeEnum.INSERT)
    @ApiOperation("课程/课件分类表保存")
    @PostMapping("/study/course/studyCourseClassify/save")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseClassify:save")
    public RespBody<String> saveStudyCourseClassify(@RequestBody StudyCourseClassifyDto studyCourseClassifyDto){
        if(studyCourseClassifyDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyCourseClassifyEntity studyCourseClassifyEntity = ConvertUtil.transformObj(studyCourseClassifyDto,StudyCourseClassifyEntity.class);
        //todo 校验同级是否有重名
        if(studyCourseClassifyService.checkName(studyCourseClassifyEntity)){
            throw new BizException(BizErrorCode.NAME_LEVEL_EXIST_ERROR);
        }
	    if(studyCourseClassifyEntity.getParentId()!=null){
            StudyCourseClassifyEntity parent = studyCourseClassifyService.getById(studyCourseClassifyEntity.getParentId());
		    if(StrUtil.isEmpty(parent.getParents())){
                studyCourseClassifyEntity.setParents(parent.getId()+"");
		    }else{
                studyCourseClassifyEntity.setParents(parent.getParents()+","+parent.getId());
		    }
	    }
        studyCourseClassifyEntity.setStatus(YesNoEnum.YES.getCode());
        if(studyCourseClassifyService.save(studyCourseClassifyEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 课程/课件分类表编辑
     * @param studyCourseClassifyDto 课程/课件分类表实体类
     * @return
     */
    @CastleLog(operLocation="课程/课件分类表",operType = OperationTypeEnum.UPDATE)
    @ApiOperation("课程/课件分类表编辑")
    @PostMapping("/study/course/studyCourseClassify/edit")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseClassify:edit")
    public RespBody<String> updateStudyCourseClassify(@RequestBody StudyCourseClassifyDto studyCourseClassifyDto){
        if(studyCourseClassifyDto == null || studyCourseClassifyDto.getId() == null || studyCourseClassifyDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyCourseClassifyEntity studyCourseClassifyEntity = ConvertUtil.transformObj(studyCourseClassifyDto,StudyCourseClassifyEntity.class);
        //todo 校验同级是否有重名
        if(studyCourseClassifyService.checkName(studyCourseClassifyEntity)){
            throw new BizException(BizErrorCode.NAME_LEVEL_EXIST_ERROR);
        }
	    if(studyCourseClassifyEntity.getParentId()!=null){
	    	//校验父级是否是子集
            QueryWrapper<StudyCourseClassifyEntity> wrapper=new QueryWrapper<>();
            wrapper.like("parents",studyCourseClassifyEntity.getId());
			wrapper.eq("id",studyCourseClassifyEntity.getParentId());
            List<StudyCourseClassifyEntity> sons = studyCourseClassifyService.list(wrapper);
            if(sons!=null && sons.size()>0){
	            throw new BizException(BizErrorCode.PARENT_IS_SON_ERROR);
            }
            StudyCourseClassifyEntity parent = studyCourseClassifyService.getById(studyCourseClassifyEntity.getParentId());
		    if(StrUtil.isEmpty(parent.getParents())){
                studyCourseClassifyEntity.setParents(parent.getId()+"");
		    }else{
                studyCourseClassifyEntity.setParents(parent.getParents()+","+parent.getId());
		    }
	    }
        studyCourseClassifyEntity.setStatus(YesNoEnum.YES.getCode());
        if(studyCourseClassifyService.updateById(studyCourseClassifyEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 课程/课件分类表删除
     * @param id
     * @return
     */
    @CastleLog(operLocation="课程/课件分类表",operType = OperationTypeEnum.DELETE)
    @ApiOperation("课程/课件分类表删除")
    @PostMapping("/study/course/studyCourseClassify/delete")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseClassify:delete")
    public RespBody<String> deleteStudyCourseClassify(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        //校验是否绑定已上架课程
        StudyCourseDto studyCourseDto = new StudyCourseDto();
        studyCourseDto.setClassifyId(id);
        studyCourseDto.setCourseStatus(CourseStatusEnum.PUTAWAY.getCode());
        List<StudyCourseDto> courseDtos = studyCourseService.listStudyCourse(studyCourseDto);
        if(courseDtos!=null && courseDtos.size()>0){
            throw new BizException(BizErrorCode.CLASSIFY_BIND_DEL_ERROR);
        }
	    QueryWrapper<StudyCourseClassifyEntity> wrapper=new QueryWrapper<>();
	    wrapper.eq("id",id);
	    wrapper.or().like("parents",id);
	    if(studyCourseClassifyService.remove(wrapper)) {
            //删除相关课件和课程
            studyCourseService.delByClassifyId(id);
            studyCoursewareService.delByClassifyId(id);
            return RespBody.data("删除成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


//    /**
//     * 课程/课件分类表批量删除
//     * @param ids
//     * @return
//     */
//    @CastleLog(operLocation="课程/课件分类表",operType = OperationTypeEnum.DELETE)
//    @ApiOperation("课程/课件分类表批量删除")
//    @PostMapping("/study/course/studyCourseClassify/deleteBatch")
//    @ResponseBody
//    @RequiresPermissions("study:course:studyCourseClassify:deleteBatch")
//    public RespBody<String> deleteStudyCourseClassifyBatch(@RequestBody List<Long> ids){
//        if(ids == null || ids.size()<1){
//            throw new BizException(GlobalRespCode.PARAM_MISSED);
//        }
//	    QueryWrapper<StudyCourseClassifyEntity> wrapper=new QueryWrapper<>();
//	    wrapper.in("id",ids);
//	    for(Long d:ids){
//		    wrapper.or().like("parents",d);
//	    }
//	    if(studyCourseClassifyService.remove(wrapper)) {
//            return RespBody.data("删除成功");
//        }else{
//            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
//        }
//    }

    /**
     * 课程/课件分类表详情
     * @param id 课程/课件分类表id
     * @return
     */
    @CastleLog(operLocation="课程/课件分类表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("课程/课件分类表详情")
    @GetMapping("/study/course/studyCourseClassify/info")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseClassify:info")
    public RespBody<StudyCourseClassifyDto> infoStudyCourseClassify(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyCourseClassifyDto studyCourseClassifyDto =  studyCourseClassifyService.getByIdExtends(id);

        return RespBody.data(studyCourseClassifyDto);
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation="课程/课件分类表",operType = OperationTypeEnum.EXPORT)
	@PostMapping("/study/course/studyCourseClassify/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<StudyCourseClassifyDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<StudyCourseClassifyDto> list = studyCourseClassifyService.listStudyCourseClassify(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}


}
